import Vue from 'vue'
import axios from 'axios'

// 设置超时时长
axios.defaults.timeout = '60000'

// request拦截器
axios.interceptors.request.use((config) => {
  return config
}, (error) => {
  return Promise.reject(error)
})

// responese拦截器
axios.interceptors.response.use((res) => {
  return res
}, (error) => {
  Vue.$message.error(error.toString())
  return Promise.reject(error)
})

/**
 * 设置请求header
 * @param {Object} headers
 */
const setHeader = (headers) => {
  for (const key in headers) {
    axios.defaults.headers[key] = headers[key]
  }
}

/**
 * POST请求
 * @param {String} url 地址
 * @param {Object} params 参数
 * @param {Object} headers headers
 */
export const methodPost = (url, params, headers = {}) => {
  return new Promise((resolve, reject) => {
    setHeader(headers)
    axios.post(url, params).then((response) => {
      resolve(response.data)
    }).catch((error) => {
      reject(error)
    })
  })
}

/**
 * 文件上传
 * @param {String} url 地址
 * @param {File} file 文件
 */
export const methodUpload = (url, file) => {
  return new Promise((resolve, reject) => {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('currentDate', Date.now())
    axios.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then((response) => {
      resolve(response.data)
    }).catch((error) => {
      reject(error)
    })
  })
}